package client;

import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;

import javax.crypto.SecretKey;

import messages.ChatMessage;
import util.Network;

public class ClientSendThread implements Runnable {

	private Socket sock;
	private long sessionID;
	private String sender;
	private SecretKey key;
	
	public ClientSendThread(Socket sock, String sender){
		this.sock = sock;
		this.sender = sender;
	}
	public void setSessionID(long sessionID) {
		this.sessionID = sessionID;
	}
	public long getSessionID() {
		return sessionID;
	}
	
	public void run() {
		Scanner scan = new Scanner(System.in);
		for(;;){
			//System.out.print("Message to Send:  ");
			String message = scan.nextLine();
			
			ChatMessage cmsg = new ChatMessage(this.sender, this.sessionID, message);
			try {
				byte[] serialized = Network.serialize(cmsg);
				if(key != null) {
					serialized = Network.encrypt(key, serialized);
				}
				Network.sendBytes(this.sock, serialized);
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
				System.out.println("Server connection lost; exiting.");
				System.exit(0);
			}
			
		}

	}
	public void setKey(SecretKey key) {
		this.key = key;
	}
	public SecretKey getKey() {
		return key;
	}

}
